<template>
  <div class="app-container">
    <el-card shadow="never">
      <div class="flex-x-between mb-10px">
        <div>
          <el-button v-hasPerm="['/admin/content/ad/add']" type="success" icon="plus" @click="handleOpenDialog()">
            新增
          </el-button>
          <!--  -->
          <el-button v-hasPerm="'/admin/content/ad/del'" type="danger" icon="delete" :disabled="selectIds.length === 0"
            @click="handleDelete()">
            批量删除
          </el-button>
        </div>
      </div>
      <el-table ref="dataTableRef" v-loading="loading" :data="pageData" highlight-current-row
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="图片" width="200" align="center">
          <template #default="scope">
            <img :src="scope.row.cover" alt="" width="60px" height="60px">
          </template>

        </el-table-column>
        <el-table-column label="排序" prop="sort" width="100" align="center" />
        <el-table-column align="center" label="状态" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.show_status == 1" type="success">显示</el-tag>
            <el-tag v-else type="info">隐藏</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="跳转方式" min-width="200" align="center">
          <template #default="scope">
            <span v-if="scope.row.jump_method == 2">内部跳转</span>
            <span v-else-if="scope.row.jump_method == 3">外链</span>
            <span v-else>无动作</span>
          </template>
        </el-table-column>
        <el-table-column label="跳转地址" prop="jump_url" min-width="200" align="center" />
        <el-table-column align="center" fixed="right" label="操作" width="180">
          <template #default="scope">
            <el-button v-hasPerm="'/admin/content/ad/update'" type="primary" size="small" link
              @click="handleOpenDialog(scope.row)">
              编辑
            </el-button>
            <el-button v-hasPerm="'/admin/content/ad/del'" type="danger" icon="delete" link size="small"
              @click="handleDelete(scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

    </el-card>

    <!-- 新增轮播 -->
    <el-dialog :close-on-click-modal="false" v-model="dialog.visible" :title="dialog.title" destroy-on-close
      append-to-body width="50%" top="12%" @close="handleCloseDialog">
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="文字" prop="name">
          <el-input v-model="formData.name" placeholder="请输入文字" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="formData.sort" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="唯一标识" prop="show_status">
          <el-radio-group v-model="formData.show_status">
            <el-radio :value="1">显示</el-radio>
            <el-radio :value="2">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="图片" prop="cover">
          <single-upload :limit="1" v-model="formData.cover" />
        </el-form-item>
        <el-form-item label="跳转状态" prop="jump_method">
          <el-radio-group v-model="formData.jump_method" @change="hanldeJumpMethod">
            <el-radio :value="1">不跳转</el-radio>
            <el-radio :value="2">站内页面</el-radio>
            <el-radio :value="3">站外</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="formData.jump_method != 1" label="跳转地址" prop="jump_url">
          <el-input v-model="formData.jump_url" placeholder="请输入跳转地址" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "AdGroupList",
  inheritAttrs: false,
});


import adGroupAPI, { adGroupPageQuery, PageVO } from "@/api/system/adGroup";
import SingleUpload from "@/components/Upload/fenpianUpload.vue";
const noticeDetailRef = ref();
const route = useRoute();
const formRef = ref(ElForm);
const pageData = ref<PageVO[]>([]);

// 选中的用户ID
const selectIds = ref<number[]>([]);
const loading = ref(false);

const queryParams = reactive<adGroupPageQuery>({
  page: 1,
  ps: 10,
});

const dialog = reactive({
  visible: false,
  title: "新增",
});

const hanldeJumpMethod = (e: any) => {
  if (e == 1) {
    formData.jump_url = ''
  }
}

const formData = reactive<any>({
  show_status: 2,
  jump_method: 1
});

// 正则验证
const rules = reactive({
  name: [{ required: true, message: "图组名称不能为空", trigger: "blur" }],
  code: [{ required: true, message: "code不能为空", trigger: "blur" }]
});

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = undefined;
}

// 提交表单（防抖）
const handleSubmit = useDebounceFn(() => {
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      const userId = formData.id;
      loading.value = true;

      formData.group_id = route.query.id;
      if (userId) {
        adGroupAPI.updateAdGroupList(formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        adGroupAPI.addAdGroupList(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}, 1000);

/**
 * 删除
 *
 * @param id  ID
 */
function handleDelete(id?: number) {
  let userIds = id ? [id] : selectIds.value;
  if (!userIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除用户?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    function () {
      loading.value = true;
      adGroupAPI.deleteAdGroupListByIds({ ids: userIds })
        .then(() => {
          ElMessage.success("删除成功");
          handleQuery();
        })
        .finally(() => (loading.value = false));
    },
    function () {
      ElMessage.info("已取消删除");
    }
  );
}

/**
 * 打开弹窗
 *
 * @param id 用户ID
 */
async function handleOpenDialog(data?: any) {
  dialog.visible = true;
  if (data) {
    console.log(data);
    Object.assign(formData, { ...data });
    dialog.title = "修改";
  } else {
    dialog.title = "新增";
  }
}

// 选中项发生变化
function handleSelectionChange(selection: any[]) {
  selectIds.value = selection.map((item) => item.id);
}

/** 查询通知公告 */
function handleQuery() {
  loading.value = true;
  queryParams.group_id = route.query.id;
  adGroupAPI.getAdGroupListPage(queryParams)
    .then((data) => {
      pageData.value = data.lists;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置通知公告查询 */
function handleResetQuery() {
  formRef.value!.resetFields();
  queryParams.page = 1;
  handleQuery();
}

function viewNoticeDetail(id: string) {
  noticeDetailRef.value.openNotice(id);
}

onMounted(() => {
  handleQuery();
});
</script>
